﻿//======================================================================
//
//        Copyright (C) 2007-2008 三月软件工作室    
//        All rights reserved
//
//        filename :CreateProperty
//        description :
//
//        created by 侯垒 at  2009-11-13 11:37:06
//        http://houleixx.cnblogs.com
//
//======================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Entity.Core
{
    /// <summary>
    /// 生成一个属性
    /// </summary>
    class CreateProperty
    {
        /// <summary>
        /// 生成属性
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        public static string CreateCode(DataRow row)
        {
            CodeVersion codeVersion = new CodeVersion();

            string columnName = row["ColumnName"].ToString();//列名
            string dataType = row["DataType"].ToString();  //类型
            string allowDbNull = row["AllowDbNull"].ToString();//是否允许为空
            StringBuilder sb = new StringBuilder();

            //声明变量
            if (codeVersion.IsVersion2)
            {
                sb.AppendFormat("    {0}{1} {2}", GetTypeName(dataType), allowDbNull == "True" ? "?" : "", "_" + columnName+";");
                sb.AppendLine();
            }
            sb.AppendFormat(@"    public {0}{1} {2}", GetTypeName(dataType), allowDbNull == "True" ? "?" : "", columnName);
            if (codeVersion.IsVersion2)
            {
                sb.AppendLine();
                sb.Append("    {");
                sb.AppendLine();
                sb.Append("        get");
                sb.Append("{");
                sb.AppendFormat("return {0};", "_" + columnName);
                sb.Append("}");
                sb.AppendLine();
                sb.Append("        set");
                sb.Append("{");
                sb.AppendFormat("{0} = value;", "_" + columnName);
                sb.Append("}");
                sb.AppendLine();
                sb.Append("    }");
            }
            else
            {
                sb.Append("{get;set;}");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 从全称得到简短类型
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private static string GetTypeName(string type)
        {
            return type.Substring(type.LastIndexOf(".") + 1);
        }
    }
}